Skip to content

Improve ConsoleCancellationManager with process termination timeout#17251

Merged
JamesNK merged 6 commits into
mainfrom
jamesnk/cli-process-termination-handler
May 19, 2026
Merged

Improve ConsoleCancellationManager with process termination timeout#17251
JamesNK merged 6 commits into
mainfrom
jamesnk/cli-process-termination-handler

Conversation

@JamesNK
Copy link
Copy Markdown
Member

@JamesNK JamesNK commented May 19, 2026

Summary

Errors were caused by a race between System.Commandline built-in cancellaiton handling and Aspire CLIs. Disabled System.Commandline by removing its timeout, and moved timeout feature to our type.


Merges improvements from System.CommandLine.ProcessTerminationHandler into ConsoleCancellationManager to provide a graceful shutdown timeout when the CLI receives termination signals.

Changes

  • Process termination timeout (5s): After a signal is received and cancellation is requested, the manager waits up to 5 seconds for the running command to finish gracefully before signaling forced termination.
  • PosixSignalRegistration for both SIGINT and SIGTERM: Previously only SIGTERM used PosixSignalRegistration; now both signals use the preferred API uniformly (with fallback to Console.CancelKeyPress + AppDomain.ProcessExit on unsupported platforms).
  • Task.WhenAny racing: The main invocation races the handler task against the ProcessTerminationCompletionSource so the process exits promptly with the correct signal exit code (130 for SIGINT, 143 for SIGTERM) if the handler doesn't finish within the timeout.

Fixes

Merge improvements from System.CommandLine ProcessTerminationHandler:

- Add processTerminationTimeout (5s) for graceful shutdown after signals

- Use PosixSignalRegistration for both SIGINT and SIGTERM

- Add AppDomain.ProcessExit handler for fallback platforms

- Wait for handler task completion within timeout before forced exit

- Race handler task against ProcessTerminationCompletionSource via Task.WhenAny

Fixes #17203

Fixes #17223
Copilot AI review requested due to automatic review settings May 19, 2026 07:21
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates Aspire CLI process-termination handling to more closely match System.CommandLine’s ProcessTerminationHandler, aiming to cancel gracefully on termination signals and, after a timeout, force termination with a signal-appropriate exit code.

Changes:

  • Adds a 5-second graceful shutdown timeout via ConsoleCancellationManager and a termination completion source.
  • Switches to using PosixSignalRegistration for SIGINT and SIGTERM (with a fallback path on some platforms).
  • Updates Program.Main to race command execution against a termination completion task and disables System.CommandLine’s process-termination timeout handling.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
src/Aspire.Cli/Program.cs Uses the new cancellation manager timeout behavior and races handler completion vs. termination completion for exit behavior.
src/Aspire.Cli/ConsoleCancellationManager.cs Implements SIGINT/SIGTERM handling plus a graceful shutdown wait and forced termination signaling.

Comment thread src/Aspire.Cli/ConsoleCancellationManager.cs
Comment thread src/Aspire.Cli/ConsoleCancellationManager.cs Outdated
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 19, 2026

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 17251

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 17251"

@JamesNK
Copy link
Copy Markdown
Member Author

JamesNK commented May 19, 2026

PR Testing Report

PR Information

CLI Version Verification

  • Expected Commit: 60df3ef28a47822f6feb210065eaac0c36e676e3
  • Installed Version: 13.4.0-dev (built from worktree at commit 60df3ef28)
  • Status: ✅ Verified (local build from correct commit)

Changes Analyzed

Files Changed

  • src/Aspire.Cli/Commands/BaseCommand.cs - Minor cast removal ((int) removed from CliExitCodes.MissingRequiredArgument)
  • src/Aspire.Cli/ConsoleCancellationManager.cs - Major rewrite (+90/-20 lines)
  • src/Aspire.Cli/Program.cs - Handler task racing & timeout integration (+13/-3)

Change Categories

  • CLI changes detected (core signal handling and process termination)
  • Hosting integration changes
  • Dashboard changes
  • Template changes
  • Client/Component changes
  • Test changes

Test Scenarios Executed

Scenario 1: Basic CLI Functionality

Objective: Verify CLI still works normally (no regressions)
Status: ✅ Passed

Steps:

  1. Built CLI from PR branch commit 60df3ef28
  2. Ran aspire --version13.4.0-dev
  3. Ran aspire --help → All commands listed correctly

Observations:

  • All commands present and correctly formatted
  • No startup errors or signal-handling crashes

Scenario 2: Start and Graceful Stop

Objective: Verify aspire start + aspire stop work with the new cancellation architecture
Status: ✅ Passed

Steps:

  1. Built TestShop.AppHost from playground
  2. Ran aspire start --apphost <TestShop> → AppHost started (PID 38996, Dashboard on :16319)
  3. Ran aspire describe → All 15 resources visible (containers + projects)
  4. Ran aspire stop → Stopped successfully in 1.94 seconds, exit code 0

Observations:

  • AppHost started and connected to Dashboard without issues
  • aspire stop sent graceful shutdown signal and completed quickly
  • No orphaned processes after stop

Scenario 3: Ctrl+C / Signal Termination (Core PR behavior)

Objective: Test SIGINT (Ctrl+C) triggers graceful shutdown within the 5-second timeout
Status: ✅ Passed

Steps:

  1. Started aspire run as a child process with redirected output
  2. Waited for "Press CTRL+C to stop" message (AppHost fully running)
  3. Sent GenerateConsoleCtrlEvent(CTRL_C_EVENT) via Win32 API
  4. Measured time to process exit

Evidence:

  • Process received signal and printed: "🛑 Stopping Aspire."
  • Exit code: 0 (graceful exit, not forced termination)
  • Exit time: 0.28 seconds (well within the 5-second processTerminationTimeout)
  • No orphaned aspire or AppHost processes remained

Observations:

  • The new PosixSignalRegistration for SIGINT correctly receives the Windows CTRL_C_EVENT
  • Cancellation flows through to the handler task which completes quickly
  • The ProcessTerminationCompletionSource timeout (5s) was not triggered (handler finished fast)
  • Exit code is 0 (graceful), not 130 (forced SIGINT exit), meaning the handler completed before timeout

Summary

Scenario Status Notes
Basic CLI Functionality ✅ Passed Version + help work
Start and Graceful Stop ✅ Passed Stop in 1.9s, exit code 0
Ctrl+C Signal Termination ✅ Passed Graceful exit in 0.28s

Overall Result

✅ PR VERIFIED

The ConsoleCancellationManager improvements work as designed:

  • SIGINT is correctly handled via PosixSignalRegistration on Windows
  • The handler task completes gracefully before the 5-second timeout
  • No race conditions observed between signal handling and process exit
  • System.CommandLine's built-in termination handler is correctly disabled (ProcessTerminationTimeout = null)

Comment thread src/Aspire.Cli/ConsoleCancellationManager.cs Outdated
Comment thread src/Aspire.Cli/ConsoleCancellationManager.cs
@JamesNK JamesNK enabled auto-merge (squash) May 19, 2026 14:26
@JamesNK JamesNK merged commit bffffd8 into main May 19, 2026
891 of 897 checks passed
@github-actions github-actions Bot added this to the 13.4 milestone May 19, 2026
@github-actions
Copy link
Copy Markdown
Contributor

CLI E2E Tests unknown — 92 passed, 0 failed, 2 unknown (commit f58059b)

View all recordings
Status Test Recording
AddPackageInteractiveWhileAppHostRunningDetached ▶️ View recording
AddPackageWhileAppHostRunningDetached ▶️ View recording
AgentCommands_AllHelpOutputs_AreCorrect ▶️ View recording
AgentInitCommand_DefaultSelection_InstallsDefaultSkills ▶️ View recording
AgentInitCommand_MigratesDeprecatedConfig ▶️ View recording
AspireAddPackageVersionToDirectoryPackagesProps ▶️ View recording
AspireInitSingleFileAppHostRunsViaDotnetRunAppHost ▶️ View recording
AspireInitWithExistingAppHostDirRecreatesMissingNuGetConfigAndPreservesFiles ▶️ View recording
AspireInitWithSolutionFileGeneratesAppHostThatBuildsAgainstChannelHive ▶️ View recording
AspireUpdateRemovesAppHostPackageVersionFromDirectoryPackagesProps ▶️ View recording
AspireUpdateRemovesOrphanAppHostPackageVersionWhenSdkAlreadyCurrent ▶️ View recording
Banner_DisplayedOnFirstRun ▶️ View recording
Banner_DisplayedWithExplicitFlag ▶️ View recording
Banner_NotDisplayedWithNoLogoFlag ▶️ View recording
CertificatesClean_RemovesCertificates ▶️ View recording
CertificatesTrust_WithNoCert_CreatesAndTrustsCertificate ▶️ View recording
CertificatesTrust_WithUntrustedCert_TrustsCertificate ▶️ View recording
ConfigSetGet_CreatesNestedJsonFormat ▶️ View recording
CreateAndRunAspireStarterProject ▶️ View recording
CreateAndRunAspireStarterProjectWithBundle ▶️ View recording
CreateAndRunEmptyAppHostProject ▶️ View recording
CreateAndRunJavaEmptyAppHostProject ▶️ View recording
CreateAndRunJsReactProject ▶️ View recording
CreateAndRunPythonReactProject ▶️ View recording
CreateAndRunTypeScriptEmptyAppHostProject ▶️ View recording
CreateAndRunTypeScriptStarterProject ▶️ View recording
CreateJavaAppHostWithViteApp ▶️ View recording
CreateTypeScriptAppHostWithViteApp_UsesConfiguredToolchain ▶️ View recording
DashboardRunWithOtelTracesReturnsNoTraces ▶️ View recording
DeployK8sBasicApiService ▶️ View recording
DeployK8sWithExternalHelmChart ▶️ View recording
DeployK8sWithGarnet ▶️ View recording
DeployK8sWithMongoDB ▶️ View recording
DeployK8sWithMySql ▶️ View recording
DeployK8sWithPostgres ▶️ View recording
DeployK8sWithRabbitMQ ▶️ View recording
DeployK8sWithRedis ▶️ View recording
DeployK8sWithSqlServer ▶️ View recording
DeployK8sWithValkey ▶️ View recording
DeployTypeScriptAppToKubernetes ▶️ View recording
DescribeCommandResolvesReplicaNames ▶️ View recording
DescribeCommandShowsRunningResources ▶️ View recording
DetachFormatJsonProducesValidJson ▶️ View recording
DetachFormatJsonProducesValidJsonWhenRestartingExistingInstance ▶️ View recording
DoListStepsShowsPipelineSteps ▶️ View recording
DocsCommand_RendersInteractiveMarkdownFromLocalSource ▶️ View recording
DoctorCommand_DetectsDeprecatedAgentConfig ▶️ View recording
DoctorCommand_TypeScriptAppHostReportsMissingConfiguredToolchain ▶️ View recording
DoctorCommand_WithSslCertDir_ShowsTrusted ▶️ View recording
DoctorCommand_WithoutSslCertDir_ShowsPartiallyTrusted ▶️ View recording
GlobalMigration_HandlesCommentsAndTrailingCommas ▶️ View recording
GlobalMigration_HandlesMalformedLegacyJson ▶️ View recording
GlobalMigration_PreservesAllValueTypes ▶️ View recording
GlobalMigration_SkipsWhenNewConfigExists ▶️ View recording
GlobalSettings_MigratedFromLegacyFormat ▶️ View recording
InitTypeScriptAppHost_AugmentsExistingViteRepoAtRoot ▶️ View recording
InteractiveCSharpInitCreatesExpectedFiles ▶️ View recording
InvalidAppHostPathWithComments_IsHealedOnRun ▶️ View recording
LatestCliCanStartStableChannelAppHost ▶️ View recording
LatestCliCanStartStableChannelTypeScriptAppHost ▶️ View recording
LegacySettingsMigration_AdjustsRelativeAppHostPath ▶️ View recording
LogLevelTrace_ProducesTraceEntriesInCliLogFile ▶️ View recording
LogsCommandShowsResourceLogs ▶️ View recording
OtelLogsReturnsStructuredLogsFromStarterApp ▶️ View recording
OtelLogsReturnsStructuredLogsFromStarterAppIsolated ▶️ View recording
PsCommandListsRunningAppHost ▶️ View recording
PsFormatJsonOutputsOnlyJsonToStdout ▶️ View recording
PublishWithConfigureEnvFileUpdatesEnvOutput ▶️ View recording
PublishWithDockerComposeServiceCallbackSucceeds ▶️ View recording
PublishWithoutOutputPathUsesAppHostDirectoryDefault ▶️ View recording
ResourceCommand_FailedExecution_DisplaysAppHostLogPathAndLogContainsEntries ▶️ View recording
ResourceCommand_FailsWhenInteractionServiceIsRequired ▶️ View recording
ResourceCommand_SetAndDeleteParameterUpdatesDescribeOutput ▶️ View recording
RestoreGeneratesSdkFiles ▶️ View recording
RestoreGeneratesSdkFiles_WithConfiguredToolchain ▶️ View recording
RestoreRefreshesGeneratedSdkAfterAddingIntegration ▶️ View recording
RestoreSupportsConfigOnlyHelperPackageAndCrossPackageTypes ▶️ View recording
RunFromParentDirectory_UsesExistingConfigNearAppHost ▶️ View recording
RunPublishFailureScenarioAsync ▶️ View recording
RunReportsSyntaxErrorsForDotNetAppHost ▶️ View recording
RunReportsSyntaxErrorsForTypeScriptAppHost ▶️ View recording
SecretCrudOnDotNetAppHost ▶️ View recording
SecretCrudOnTypeScriptAppHost ▶️ View recording
StagingChannel_ConfigureAndVerifySettings_ThenSwitchChannels ▶️ View recording
StartAndWaitForTypeScriptSqlServerAppHostWithNativeAssets ▶️ View recording
StartReportsSyntaxErrorsForDotNetAppHost ▶️ View recording
StartReportsSyntaxErrorsForTypeScriptAppHost ▶️ View recording
StopAllAppHostsFromAppHostDirectory ▶️ View recording
StopJavaPolyglotAppHostUsingApphostDirectory ▶️ View recording
StopNonInteractiveSingleAppHost ▶️ View recording
StopTypeScriptPolyglotAppHostUsingApphostDirectory ▶️ View recording
StopWithNoRunningAppHostExitsSuccessfully ▶️ View recording
UnAwaitedChainsCompileWithAutoResolvePromises ▶️ View recording
UpdateProjectChannelToStable_TypeScript_PicksUpStablePackages ▶️ View recording

📹 Recordings uploaded automatically from CI run #26102544581

@aspire-repo-bot
Copy link
Copy Markdown
Contributor

✅ No documentation update needed.

docs_optional → internal_refactor

No signals triggered (signal_count == 0). The PR improves the internal ConsoleCancellationManager class to handle process termination signals (SIGINT/SIGTERM) more robustly — adding a 5-second graceful shutdown timeout, switching to PosixSignalRegistration uniformly, and fixing a race with System.CommandLine's built-in cancellation. No new CLI flags, options, public APIs, or user-facing configuration were introduced. All 3 changed files (ConsoleCancellationManager.cs, Program.cs, and a test file) are internal implementation details of the CLI's shutdown logic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

4 participants